using Microsoft.AspNetCore.Mvc;
using ReportToolAPI.Models;
using ReportToolAPI.Services;

namespace ReportToolAPI.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class DatabaseController : ControllerBase
    {
        private readonly DatabaseConfigService _configService;

        public DatabaseController(DatabaseConfigService configService)
        {
            _configService = configService;
        }

        /// <summary>
        /// 测试数据库连接
        /// </summary>
        [HttpPost("test-connection")]
        public async Task<IActionResult> TestConnection([FromBody] TestConnectionRequest request)
        {
            try
            {
                var (success, message) = await DatabaseTestService.TestConnectionAsync(request);
                
                if (success)
                {
                    return Ok(ApiResponse<object>.Ok(null, message));
                }
                else
                {
                    return Ok(ApiResponse<object>.Fail(message));
                }
            }
            catch (Exception ex)
            {
                return Ok(ApiResponse<object>.Fail($"测试连接异常: {ex.Message}"));
            }
        }

        /// <summary>
        /// 获取数据库配置列表
        /// </summary>
        [HttpGet("list")]
        public IActionResult GetList()
        {
            try
            {
                var databases = _configService.GetAll();
                return Ok(ApiResponse<List<DatabaseConfig>>.Ok(databases));
            }
            catch (Exception ex)
            {
                return Ok(ApiResponse<List<DatabaseConfig>>.Fail($"获取列表失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 添加数据库配置
        /// </summary>
        [HttpPost("add")]
        public async Task<IActionResult> Add([FromBody] DatabaseConfig config)
        {
            try
            {
                // 先测试连接
                var testRequest = new TestConnectionRequest
                {
                    DatabaseName = config.DatabaseName,
                    Ip = config.Ip,
                    Port = config.Port,
                    Username = config.Username,
                    Password = config.Password
                };

                var (success, message) = await DatabaseTestService.TestConnectionAsync(testRequest);
                
                if (!success)
                {
                    return Ok(ApiResponse<object>.Fail($"数据库连接测试失败: {message}"));
                }

                // 连接成功，保存配置
                var newConfig = _configService.Add(config);
                return Ok(ApiResponse<DatabaseConfig>.Ok(newConfig, "添加成功"));
            }
            catch (Exception ex)
            {
                return Ok(ApiResponse<object>.Fail($"添加失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 更新数据库配置
        /// </summary>
        [HttpPut("update/{id}")]
        public async Task<IActionResult> Update(int id, [FromBody] DatabaseConfig config)
        {
            try
            {
                // 先测试连接
                var testRequest = new TestConnectionRequest
                {
                    DatabaseName = config.DatabaseName,
                    Ip = config.Ip,
                    Port = config.Port,
                    Username = config.Username,
                    Password = config.Password
                };

                var (success, message) = await DatabaseTestService.TestConnectionAsync(testRequest);
                
                if (!success)
                {
                    return Ok(ApiResponse<object>.Fail($"数据库连接测试失败: {message}"));
                }

                // 连接成功，更新配置
                var result = _configService.Update(id, config);
                
                if (result)
                {
                    return Ok(ApiResponse<object>.Ok(null, "更新成功"));
                }
                else
                {
                    return Ok(ApiResponse<object>.Fail("配置不存在", 404));
                }
            }
            catch (Exception ex)
            {
                return Ok(ApiResponse<object>.Fail($"更新失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 删除数据库配置
        /// </summary>
        [HttpDelete("delete/{id}")]
        public IActionResult Delete(int id)
        {
            try
            {
                var result = _configService.Delete(id);
                
                if (result)
                {
                    return Ok(ApiResponse<object>.Ok(null, "删除成功"));
                }
                else
                {
                    return Ok(ApiResponse<object>.Fail("配置不存在", 404));
                }
            }
            catch (Exception ex)
            {
                return Ok(ApiResponse<object>.Fail($"删除失败: {ex.Message}"));
            }
        }
    }
}




